package com.janal.controller;

import com.janal.model.dao.user.User;
import com.janal.model.service.login.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取用户输入的账号密码
        System.out.println("haha");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User getuser = new User(username,password);
        //调用service进行用户匹配
        LoginServiceImpl lsi = new LoginServiceImpl();
        User resultuser = lsi.login(getuser);
        if(resultuser == null){
            req.setAttribute("error","该用户不存在，请先注册！");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else if(resultuser.getPassword() == null){
            req.setAttribute("error","密码错误！");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else{      //登录成功
            req.getSession().setAttribute("usersession",resultuser);
            resp.sendRedirect("/s/success.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
